var caseObj, caseDataObj, videoObj, audioObj, photoObj, myChart, nowObj;
var selectKey = [
    'case_count_obj',
    'case_data_count_obj',
    'video_count_obj',
    'photo_count_obj',
    'audio_count_obj'
];
$(document).ready(function () {
    handleTimeShowOrHide('1')
    /**
     * 刷新或搜索
     */
    $('body').delegate('.action-reload', 'click', function () {
        var cluster_id = $('select[name=cluster_id]').val();
        var video_type = $('select[name=video_type]').val();
        var createTimeStart = $("#createTimeStart").val();
        var createTimeEnd = $("#createTimeEnd").val();
        var key = $('input[name=key]').val();

        var params = 'cluster_id=' + cluster_id + '&video_type=' + video_type + '&startTime=' +
            createTimeStart + '&endTime=' + createTimeEnd + '&key=' + key;
        window.location.href = '/archiveadmin/statShow?' + params;
    });

    $('.action-refresh').on('click', function () {
        getData();
    })

    /**
     * 搜索对回车的支持
     */
    $("input[name=key]").on('keypress', function (event) {
        if (event.which == '13' && $(this).val()) {
            getData();
            return false;
        }
    });

    /**
     * datepicker
     */
    $(".datepicker-input").each(function () {
        $(this).datepicker({
            language: "zh-CN",
            autoclose: true
        });
    });

    /**
     * 切换统计类型
     */
    $('.statisticsType').on('change', function () {
        handleTimeShowOrHide($(this).val())
    })

    $('input[name=sign_checkbox]').on('change', function () {
        setOption(nowObj)
    })

    $('input[name=year_sign_checkbox]').on('change', function () {
        console.log($(this).is(':checked'));
        setOption(nowObj)
    })

    /**
     * 初始化地区选单
     */
    $("select.region").each(function (k) {
        var pid = $(this).attr('data-init');
        if (k == 0) {
            pid = pid ? pid : 3743;
        }
        if (pid > 0) {
            getRegionByPid(pid, $(this));
        }
    });

    var timer = null;
    getRegionId(timer)
});

function setSelectKey(key) {
    selectKey = [key];
    setOption(nowObj);
}

function getRegionId(timer) {
    if (getRegionVal() > 0) {
        clearInterval(timer);
        getData()
    } else {
        timer = setInterval(function () {
            getRegionId(timer)
        }, 500)
    }
}

function getData() {
    var params = fetchParams()
    $.ajax({
        type: 'post',
        url: '/archiveadmin/statShow/fetchStatisticsData',
        data: params,
        dataType: 'json',
        timeout: 60000,
        success: function (data) {
            if (data.status == 0) {
                handleResultData(data.data)
            } else {
                alert('分析数据错误，请稍后重试');
            }
        }
    });
}

function handleResultData(obj) {
    caseObj = obj.case_count_obj
    caseDataObj = obj.case_data_count_obj
    videoObj = obj.video_count_obj
    audioObj = obj.audio_count_obj
    photoObj = obj.photo_count_obj

    // 处理数据 赋值
    $('#case_count').html(caseObj.all_count);
    $('#year_case_count').html(caseObj.all_rate * 100 + '%');

    $('#case_data_count').html(caseDataObj.all_count);
    $('#year_case_data_count').html(caseDataObj.all_rate * 100 + '%');

    $('#videotape_time').html(videoObj.all_count);
    $('#year_videotape_time').html(videoObj.all_rate * 100 + '%');

    $('#photo_count').html(photoObj.all_count);
    $('#year_photo_count').html(photoObj.all_rate * 100 + '%');

    $('#sound_count').html(audioObj.all_count);
    $('#year_sound_count').html(audioObj.all_rate * 100 + '%');

    taskRateChartsDraw(obj);
}

/**
 * 获取所有的筛选条件
 * @returns {{key: (*|jQuery), region: *, statistics_type: (*|jQuery), department_name: (*|jQuery)}}
 */
function fetchParams() {
    var params = {
        key: $('input[name=key]').val(),
        region: getRegionVal(),
        statistics_type: $('.statisticsType').val(),
        department_name: $('select[name=department_name]').val()
    }

    var timeObj = getTime()
    Object.assign(params, timeObj)
    return params
}

/**
 * 获取地区值
 * @returns {*}
 */
function getRegionVal() {
    var objList = $('select.region')
    var region_3 = objList.eq(2).val();
    var region_2 = objList.eq(1).val();
    return region_3 > 0 ? region_3 : region_2;
}

/**
 * 获取时间范围
 * @returns {{}}
 */
function getTime() {
    var result = {}
    var screen_type = $('.statisticsType').val()
    switch (screen_type) {
        case '1':
            var parentObjMonth = $('.month-screen-box')
            result.start_time = parentObjMonth.find('input[name=time_start]').val()
            result.end_time = parentObjMonth.find('input[name=time_end]').val()
            break;
        case '2':
            var parentObjQuarter = $('.quarter-screen-box')
            result.start_time = parentObjQuarter.find('input[name=time_start]').val() + '-01-01'
            result.end_time = parentObjQuarter.find('input[name=time_start]').val() + '-12-31'
            break;
        case '3':
            var parentObjYear = $('.year-screen-box')
            result.start_time = parentObjYear.find('input[name=time_start]').val() + '-01-01'
            result.end_time = parentObjYear.find('input[name=time_end]').val() + '-12-31'
            break;
        default:
            break;
    }
    return result
}

/**
 * 处理 时间选择框并初始化默认值
 * @param type
 */
function handleTimeShowOrHide(type) {
    var objList = $('.time-screen-box')
    var date = new Date();
    var nowYear = date.getFullYear();
    var nowMonth = (date.getMonth() + 1) < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1;
    switch (type) {
        case '1':
            objList.each(function () {
                if ($(this).hasClass('month-screen-box')) {
                    $(this).css('display', 'inline')
                } else {
                    $(this).css('display', 'none')
                }
            })
            var parentObjMonth = $('.month-screen-box')
            parentObjMonth.find('input[name=time_start]').datepicker('setDate', nowYear + '-01')
            parentObjMonth.find('input[name=time_end]').datepicker('setDate', nowYear + '-' + nowMonth)
            break;
        case '2':
            objList.each(function () {
                if ($(this).hasClass('quarter-screen-box')) {
                    $(this).css('display', 'inline')
                } else {
                    $(this).css('display', 'none')
                }
            })
            var parentObjQuarter = $('.quarter-screen-box')
            parentObjQuarter.find('input[name=time_start]').datepicker('setDate', new Date(nowYear + '-' + '01'))
            break;
        case '3':

            objList.each(function () {
                if ($(this).hasClass('year-screen-box')) {
                    $(this).css('display', 'inline')
                } else {
                    $(this).css('display', 'none')
                }
            })
            var parentObjYear = $('.year-screen-box')
            parentObjYear.find('input[name=time_start]').datepicker('setDate', new Date(nowYear - 3 + '-' + '01'))
            parentObjYear.find('input[name=time_end]').datepicker('setDate', new Date(nowYear + '-' + '01'))
            break;
        default:
            break;
    }
}

function getSeriesOption(obj) {
    var result = [];
    var mapList = {
        'case_count_obj': '案件数',
        'case_data_count_obj': '行动数',
        'video_count_obj': '录像时长',
        'photo_count_obj': '照片数',
        'audio_count_obj': '录音时长',
    }
    $.each(obj, function (item, value) {
        if (item != 'xLabel' && selectKey.indexOf(item) >= 0) {
            var objBar = {
                name: mapList[item],
                type: 'bar',
                data: value.case_count_list
            }

            var objLine = {
                name: mapList[item] + '同比率',
                type: 'line',
                data: value.rate_list
            }
            if ($('input[name=sign_checkbox]').is(':checked')) {
                result.push(objBar)
            }
            if ($('input[name=year_sign_checkbox]').is(':checked')) {
                result.push(objLine)
            }
        }
    })
    return result;
}

function setOption(obj) {
    var seriesOption = getSeriesOption(obj);
    var option = {
        title: {
            text: ''
        },
        // color: colors,
        tooltip: {
            trigger: 'axis',
            // triggerOn: 'click',
            axisPointer: {
                type: 'cross'
            },
            formatter: function (param) {
                console.log(param)
                return param[0].name + '<br/>' +
                    param[0].marker + "&nbsp;" + param[0].seriesName + "：" + param[0].value + "件" +"<br>" +
                    param[1].marker + "&nbsp;" + param[1].seriesName + "：" + param[1].value + "%<br>" +
                    param[2].marker + "&nbsp;" + param[2].seriesName + "：" + param[2].value + "个" +"<br>" +
                    param[3].marker + "&nbsp;" + param[3].seriesName + "：" + param[3].value + "%<br>" +
                    param[4].marker + "&nbsp;" + param[4].seriesName + "：" + param[4].value + "分" +"<br>" +
                    param[5].marker + "&nbsp;" + param[5].seriesName + "：" + param[5].value + "%<br>" +
                    param[6].marker + "&nbsp;" + param[6].seriesName + "：" + param[6].value + "分" +"<br>" +
                    param[7].marker + "&nbsp;" + param[7].seriesName + "：" + param[7].value + "%<br>" +
                    param[8].marker + "&nbsp;" + param[8].seriesName + "：" + param[8].value + "张" +"<br>" +
                    param[9].marker + "&nbsp;" + param[9].seriesName + "：" + param[9].value + "%";
            }
        },
        legend: {
            selectedMode: false,
            // data: ['成功率', '失败率']
        },
        grid: {
            top: 70,
            bottom: 50
        },
        xAxis: [
            {
                type: 'category',
                axisTick: {
                    alignWithLabel: true
                },
                axisLine: {
                    onZero: true
                },
                data: obj.xLabel
            }
        ],
        yAxis: [
            {
                type: 'value'
            }
        ],
        series: seriesOption
    };
    myChart.setOption(option, true);
}

/**
 * 转码完成率图表 - 绘制
 */
function taskRateChartsDraw(obj) {
    myChart = echarts.init(document.getElementById('chart_task_rate'));
    nowObj = obj;
    setOption(obj)
}
